#include "mystdio.h"

#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <unistd.h>

MyFile* buyFile(int fd, int flag)
{
    MyFile* file = (MyFile*)malloc(sizeof(MyFile));

    file->fileno = fd;
    file->flag = flag;
    file->outbufferlen = 0;
    file->flush_method = LINE_FLUSH;
    memset(file->outbuffer, 0, sizeof(file->outbuffer));

    return file;
}

MyFile* myOpen(const char* path, const char* mode)
{
    int fd = -1;
    int flag = 0;
    if(strcmp(mode, "w") == 0)
    {
        flag = O_CREAT | O_WRONLY | O_TRUNC;
        fd = open(path, flag, 0666);

    }
    else if(strcmp(mode, "a") == 0)
    {
        flag = O_CREAT | O_WRONLY | O_APPEND;
        fd = open(path, flag, 0666);
    }
    else 
    {
        //...
    }
    if(fd < 0) return NULL;
    return buyFile(fd, flag);
}

void myClose(MyFile* file)
{
    if(file->fileno < 0) return;
    if(file->outbufferlen > 0)
    {
        myFflush(file);
    }
    close(file->fileno);
    free(file);
}

int myFwrite(void* str, size_t size, size_t num, MyFile* file)
{
    int n = size * num;
    memcpy(file->outbuffer + file->outbufferlen, str, n);
    file->outbufferlen += n;
    if((file->flush_method == LINE_FLUSH) && file->outbuffer[file->outbufferlen - 1] == '\n')
    {
        myFflush(file);
    }
    return num;
}

void myFflush(MyFile* file)
{
    if(file->outbufferlen <= 0) return;
    write(file->fileno, file->outbuffer, file->outbufferlen);
    file->outbufferlen = 0;
} 

